package com.kmvc.message.adapter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.kmvc.message.activity.MessageApplication;
import com.kmvc.message.activity.MessageShowActivity;
import com.kmvc.message.database.DbHelper;
import com.kmvc.message.entity.StringEntity;
import com.kmvc.message.R;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.StatFs;
import android.text.ClipboardManager;
import android.text.util.Linkify;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.ZoomDensity;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

@SuppressWarnings("deprecation")
public class WebviewAdapternew extends BaseAdapter {

	private Context context;
	private List<com.kmvc.message.entity.StringEntity> list;
	AlertDialog.Builder builder;
	// AlertDialog al;
	private String area, datString, ids, Content;
	private View myView;
	private int size;
	private int flag = -1;
	public static WebView webView;
	
	
	String pathForPub;
	View vForPub;
	Handler handler=new Handler();
	Runnable runnable=new Runnable() 
	{	
		@Override
		public void run() {
			try 
			{
				if(pathForPub!=null)
				{
					Bitmap bitmap=BitmapFactory.decodeFile(pathForPub);
					if(bitmap==null)
					{
						handler.postDelayed(runnable, 300);
					}
					else 
					{
						vForPub.setBackgroundDrawable(null);
						vForPub.setBackgroundDrawable(new BitmapDrawable(bitmap));
						notifyDataSetChanged();
						//Toast.makeText(context, "下载完成！", Toast.LENGTH_SHORT).show();
						vForPub=null;
						pathForPub=null;
					}
				}
			} 
			catch (Exception e) 
			{
				
			}
		}
	};
	

	public WebviewAdapternew(Context context, List<StringEntity> list,
			String area, String datString) {
		this.context = context;
		this.list = list;
		this.area = area;
		this.datString = datString;
		SharedPreferences sPreferences = context.getSharedPreferences(
				"com.kmvc.message_preferences", 0);
		size = Integer.parseInt(sPreferences.getString("sizelist", "2"));

	}

	@Override
	public int getCount() {

		return list.size();
	}

	@Override
	public Object getItem(int position) {

		return list.get(position);
	}

	@Override
	public long getItemId(int position) {

		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			LayoutInflater vi = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = vi.inflate(R.layout.listitemweb, null);
		}

		TextView id = (TextView) convertView.findViewById(R.id.ids);
		TextView date = (TextView) convertView.findViewById(R.id.itemdate);
		TextView contentTextView = (TextView) convertView
				.findViewById(R.id.itemcontent);
		  webView = (WebView) convertView
				.findViewById(R.id.itemcontentweb);
	 ImageView imageView=(ImageView)convertView.findViewById(R.id.itemImg);

		// webView.getSettings().setJavaScriptEnabled(true);
		webView.setFocusable(false);
		// webView.getSettings().setUseWideViewPort(true);
		
		
		DisplayMetrics metric = context.getResources().getDisplayMetrics();
		int width=metric.widthPixels;
		
		int baseScale=100;
		if(list.get(position).getContent().startsWith("<html>"))
		{
			String content=list.get(position).getContent();
			if(content.indexOf("zoom=\"")>0)
			{
				String zoomStr=content.substring(content.indexOf("zoom=\""));
				if(zoomStr.length()>10)
				{
					String bString=zoomStr.substring(6,10);
					if(bString.indexOf("\"")>0)
					{
						bString=bString.substring(0, bString.indexOf("\""));
						try 
						{
							baseScale=Integer.parseInt(bString);
						} 
						catch (Exception e) 
						{
							
						}
					}
					bString.toString();
				}
			}
		}
        if(width>540)
        {
        	double Scale=width/480.0;
        	Scale=Scale*baseScale;
        	webView.setInitialScale((int)Scale);
        }
        else 
        {
        	webView.setInitialScale(baseScale);
		}

		webView.getSettings().setSupportZoom(true);

		if (size == 0) {
			webView.getSettings().setTextSize(WebSettings.TextSize.SMALLEST);
		} else if (size == 1) {
			webView.getSettings().setTextSize(WebSettings.TextSize.SMALLER);
		} else if (size == 2) {
			webView.getSettings().setTextSize(WebSettings.TextSize.NORMAL);
		} else if (size == 3) {
			webView.getSettings().setTextSize(WebSettings.TextSize.LARGER);
		} else {
			webView.getSettings().setTextSize(WebSettings.TextSize.LARGEST);
		}

		webView.getSettings().setDefaultZoom(ZoomDensity.FAR);
		//
		webView.getSettings().setBuiltInZoomControls(true);

		webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
		webView.setWebChromeClient(new WebChromeClient());
		webView.setWebViewClient(new WebViewClient());

		id.setText(list.get(position).getID());
		date.setText(list.get(position).getStart_Time());
		
		id.setTextColor(Color.BLACK);
		date.setTextColor(Color.BLACK);
		contentTextView.setTextColor(Color.BLACK);

		imageView.setVisibility(8);
		
		if (list.get(position).getContent().startsWith("<html>")) {
			webView.setVisibility(View.VISIBLE);
			webView.loadDataWithBaseURL(null, list.get(position).getContent(),
					"text/html", "UTF-8", "");
			webView.setOnLongClickListener(new OnLongClickListener() {

				@Override
				public boolean onLongClick(View v) {
					myView = v;
					ClickFun(list.get(position).ID, list.get(position).Content);
					return false;
				}
			});
		} 
		else 
		{
			final String contenString=list.get(position).getContent();
			if(contenString.startsWith("<Image>")&&contenString.endsWith("</Image>"))
			{
				String url=contenString.replace("<Image>", "");
				url=contenString.replace("</Image>", "");
				String[] arr=url.split("/");
				if(arr.length>2)
				{
					url=arr[arr.length-1];
					if(url!=null&&!url.equals(""))
					{
						String SDPATH = Environment.getExternalStorageDirectory().getPath();
						final String path=SDPATH+"/KMVC_MESSAGE/reportImg/"+url;
						File mfile=new File(path);
						if(mfile.exists())
						{
							Log.d("kmvc","文件存在！");
							try 
							{
								Bitmap bitmap=BitmapFactory.decodeFile(path);
								imageView.setVisibility(0);
								imageView.setBackgroundDrawable(new BitmapDrawable(bitmap));							
								
							} 
							catch (Exception e) 
							{
								
							}
							
						}
						else 
						{
							imageView.setVisibility(0);
							imageView.setBackgroundResource(R.drawable.defaultpic);
						}
						
						imageView.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(final View v) 
							{
								File file=new File(path);
								if(file.exists())
								{
									Intent it =new Intent(Intent.ACTION_VIEW); 
									Uri mUri = Uri.parse("file://"+file.getPath()); 
									it.setDataAndType(mUri, "image/*"); 
									context.startActivity(it);
								}
								else 
								{
									if(vForPub==null)
									{
										new Thread(){
											public void run()
											{
												MessageApplication application=(MessageApplication)((Activity)context).getApplication();
												DbHelper dbHelper=new DbHelper(context);
												String DowdLoadUrl=contenString.replace("<Image>", "").replace("</Image>", "");
												application.LoadReportImg(Content,list.get(position).getStart_Time(), area,DowdLoadUrl,dbHelper);
												dbHelper.close();
												vForPub=v;
												pathForPub=path;
												handler.post(runnable);
												
											}
										}.start();
									}
									else 
									{
										Toast.makeText(context, "已有任务在下载，请稍后重试！",Toast.LENGTH_LONG).show();
									}
								}
							}
						});
						
						imageView.setOnLongClickListener(new OnLongClickListener() {
							
							@Override
							public boolean onLongClick(View v) 
							{
								File file=new File(path);
								if(file.exists())
								{
									Intent intent2 = new Intent(Intent.ACTION_SEND);
									intent2.putExtra(
											Intent.EXTRA_STREAM,
											Uri.parse("file:///"+path));
									intent2.setType("image/jpeg");
									context.startActivity(Intent.createChooser(
											intent2, "发送图片至:"));
								}
								return false;
							}
						});
					}
				}
			}
			else 
			{
				contentTextView.setText(list.get(position).getContent());
				contentTextView.setVisibility(View.VISIBLE);
				if (list.get(position).getContent().contains("http://")) 
				{
					contentTextView.setAutoLinkMask(Linkify.WEB_URLS);
				}
			}

		}

		convertView.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				myView = v;
				ClickFun(list.get(position).ID, list.get(position).Content);
				return false;
			}
		});
		convertView.setBackgroundDrawable(context.getResources().getDrawable(
				R.drawable.chatfrom_bg_app_pressed));
		//incoming
		//chatfrom_bg_app_normal
		return convertView;
	}

	protected void ClickFun(String id, String conString) {

		ids = id;
		String regEx_html = "<[^>]+>";
		Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
		Matcher m_html = p_html.matcher(conString);
		Content = m_html.replaceAll("").trim();// 过滤html标签 ，去掉空格
		final AlertDialog.Builder Choicebuilder = new AlertDialog.Builder(
				context);
		Choicebuilder.setCancelable(false);
		Choicebuilder
				.setTitle("选择操作")
				// .setIcon(icLauncher)
				.setSingleChoiceItems(
						new String[] { "删除此条信息", "删除全部信息", "复制此条信息", "消息截图" },
						-1, new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								switch (which) {
								case 0:
									flag = 0;
									// showMyDialog("删除此消息？", 0);
									break;
								case 1:
									flag = 1;
									// showMyDialog("删除全部信息？", 1);
									break;
								case 2:
									flag = 2;
									// showMyDialog("复制此信息？", 2);
									break;
								case 3:
									flag = 3;
									// showMyDialog("消息截图", 3);
								}
								// dialog.dismiss();

							}
						})
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@SuppressLint("SimpleDateFormat")
					@Override
					public void onClick(DialogInterface dialog, int which) {

						DbHelper db = new DbHelper(context);
						Intent intent = new Intent(context, MessageShowActivity.class);
						intent.putExtra("area", area);
						intent.putExtra("datestring", datString);
						if (flag == 0) {
							db.deletebyid(ids);
							db.close();
							// al.dismiss();
							context.startActivity(intent);
							((Activity)context).finish();
						} else if (flag == 1) {
							// db.deleteall();
							db.delteall(area, datString);
							db.close();
							// al.dismiss();
							context.startActivity(intent);
							((Activity)context).finish();
						} else if (flag == 2) {
							ClipboardManager cmb = (ClipboardManager) context
									.getSystemService(Context.CLIPBOARD_SERVICE);
							cmb.setText(Content);
							Toast.makeText(context, "复制成功", Toast.LENGTH_LONG)
									.show();
							Intent intent2 = new Intent(Intent.ACTION_SEND);
							intent2.putExtra(Intent.EXTRA_TEXT, Content);
							intent2.setType("text/html");
							context.startActivity(Intent.createChooser(intent2,
									"发送信息至:"));
							// al.dismiss();
						} else if (flag == 3) {
							try {
								// View view =
								// ((Activity) context)
								// .getWindow()
								// .getDecorView();
								// view.setDrawingCacheEnabled(true);
								myView.setDrawingCacheEnabled(true);
								// view.buildDrawingCache();
								myView.buildDrawingCache();
								// Bitmap b1 = view
								// .getDrawingCache();
								Bitmap b2 = myView.getDrawingCache();
								int w = myView.getWidth();
								// int h=
								// myView.getHeight();
								int bt = b2.getHeight();
								// y + height must be <=
								// bitmap.height()
								Bitmap bbmBitmap = Bitmap.createBitmap(b2, 0,
										0, w, bt);
								// view.destroyDrawingCache();
								myView.destroyDrawingCache();
								// FileOutputStream fos
								// = null;
								FileOutputStream fos1 = null;
								SimpleDateFormat formatter = new SimpleDateFormat(
										"yyyyMMddHHmmss");
								Date newdate = new Date(System
										.currentTimeMillis());// 获取当前时间
								String datestringString = formatter
										.format(newdate);
								StatFs statFs = new StatFs(Environment
										.getExternalStorageDirectory()
										.getPath());
								long nBlockSize = statFs.getBlockSize();
								// 获取可供程序使用的Block的数量
								long nAvailaBlock = statFs.getAvailableBlocks();
								long nSDFreeSize = nAvailaBlock * nBlockSize
										/ 1024 / 1024;
								File destDir = new File(Environment
										.getExternalStorageDirectory()
										.toString()
										+ "/KMVC_MESSAGE");
								if (nSDFreeSize < 10) {
									Toast.makeText(
											context,
											"检测到您的SD卡剩余存储不足" + nSDFreeSize
													+ "M,请释放部分存储空间或更换更大容量的存储卡",
											Toast.LENGTH_LONG).show();
								}
								if (!destDir.exists()) {
									destDir.mkdirs();
								}
								try {
									// fos = new
									// FileOutputStream(
									// "mnt/sdcard/shoot.png");

									fos1 = new FileOutputStream(
											"mnt/sdcard/KMVC_MESSAGE/"
													+ datestringString + ".png");
									if (null != fos1) {
										bbmBitmap.compress(
												Bitmap.CompressFormat.PNG, 0,
												fos1);
										fos1.flush();
										fos1.close();
									}
								} catch (FileNotFoundException e) {
									e.printStackTrace();
								} catch (IOException e) {
									e.printStackTrace();
								}
								// b.recycle();
								// b1.recycle();
								b2.recycle();
								bbmBitmap.recycle();
								Intent intent2 = new Intent(Intent.ACTION_SEND);
								intent2.putExtra(
										Intent.EXTRA_STREAM,
										Uri.parse("file:///mnt/sdcard/KMVC_MESSAGE/"
												+ datestringString + ".png"));
								intent2.setType("image/jpeg");
								context.startActivity(Intent.createChooser(
										intent2, "发送图片至:"));
							} catch (Exception e) {

								e.printStackTrace();
								try {
									View view = ((Activity) context)
											.getWindow().getDecorView();
									view.setDrawingCacheEnabled(true);
									view.buildDrawingCache();
									Bitmap b1 = view.getDrawingCache();

									// 获取状态栏高度
									Rect frame = new Rect();
									((Activity) context)
											.getWindow()
											.getDecorView()
											.getWindowVisibleDisplayFrame(frame);
									int statusBarHeight = frame.top;

									// 获取屏幕长和高
									int width = ((Activity) context)
											.getWindowManager()
											.getDefaultDisplay().getWidth();
									int height = ((Activity) context)
											.getWindowManager()
											.getDefaultDisplay().getHeight();
									Bitmap b = Bitmap.createBitmap(b1, 0,
											statusBarHeight, width, height
													- statusBarHeight);
									view.destroyDrawingCache();
									FileOutputStream fos1 = null;
									SimpleDateFormat formatter = new SimpleDateFormat(
											"yyyyMMddHHmmss");
									Date newdate = new Date(System
											.currentTimeMillis());// 获取当前时间
									String datestringString = formatter
											.format(newdate);
									StatFs statFs = new StatFs(Environment
											.getExternalStorageDirectory()
											.getPath());
									long nBlockSize = statFs.getBlockSize();
									// 获取可供程序使用的Block的数量
									long nAvailaBlock = statFs
											.getAvailableBlocks();
									long nSDFreeSize = nAvailaBlock
											* nBlockSize / 1024 / 1024;
									File destDir = new File(Environment
											.getExternalStorageDirectory()
											.toString()
											+ "/KMVC_MESSAGE");
									if (nSDFreeSize < 10) {
										Toast.makeText(
												context,
												"检测到您的SD卡剩余存储不足"
														+ nSDFreeSize
														+ "M,请释放部分存储空间或更换更大容量的存储卡",
												Toast.LENGTH_LONG).show();
									}
									if (!destDir.exists()) {
										destDir.mkdirs();
									}
									try {

										fos1 = new FileOutputStream(
												"mnt/sdcard/KMVC_MESSAGE/"
														+ datestringString
														+ ".png");
										if (null != fos1) {
											b.compress(
													Bitmap.CompressFormat.PNG,
													0, fos1);
											fos1.flush();
											fos1.close();
										}
									} catch (FileNotFoundException ee) {
										ee.printStackTrace();
									} catch (IOException ee) {
										ee.printStackTrace();
									}
									b.recycle();
									b1.recycle();

									Intent intent2 = new Intent(
											Intent.ACTION_SEND);
									intent2.putExtra(
											Intent.EXTRA_STREAM,
											Uri.parse("file:///mnt/sdcard/KMVC_MESSAGE/"
													+ datestringString + ".png"));
									intent2.setType("image/jpeg");
									context.startActivity(Intent.createChooser(
											intent2, "发送图片至:"));
								} catch (Exception e2) {

									Toast.makeText(context, "截图失败",
											Toast.LENGTH_LONG).show();
								}
							}

							// al.dismiss();
						}

					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						flag = -1;
					}
				});

		Choicebuilder.create();
		Choicebuilder.show();

	}

}
